package org.example.component;

import cn.hutool.core.collection.CollUtil;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.example.config.ImSessionContext;
import org.example.enums.KeyEnum;
import org.example.packets.ImClientNode;
import org.example.packets.bean.Group;
import org.example.packets.bean.User;
import org.tio.core.ChannelContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 线程共享用户信息
 */
@Getter
@Accessors(chain = true)
public class LoginInfo {

    /**
     * 当前用户上下文
     */
    private ChannelContext channelContext;

    /**
     * 当前会话上下文
     */
    private ImSessionContext imSessionContext;

    /**
     * 当前节点存储信息
     */
    private ImClientNode imClientNode;

    /**
     * 当前用户信息
     */
    private User user;

    /**
     * 当前用户信息
     */
    private List<Group> groups;

    /**
     * 当前用户群组ID, 群组Map
     */
    private Map<String, Group> groupsMap;

    /**
     * 当前用户对应好友ID, 群组Map
     */
    private Map<String, Group> friendGroupMap;

    public LoginInfo setChannelContext(ChannelContext channelContext) {
        this.channelContext = channelContext;
        this.imSessionContext = (ImSessionContext) channelContext.get(KeyEnum.IM_CHANNEL_SESSION_CONTEXT_KEY.getKey());
        this.imClientNode = this.imSessionContext.getImClientNode();
        this.user = this.imClientNode.getUser();
        this.groups = CollUtil.defaultIfEmpty(this.imClientNode.getGroups(), new ArrayList<>());
        this.groupsMap = this.getGroups().stream().collect(Collectors.toMap(Group::getRoomId, x -> x));
        this.friendGroupMap = this.getGroups().stream().filter(Group::getIsFriend).collect(Collectors.toMap(Group::getFriendId, x -> x));
        return this;
    }

    public void putGroup(Group group){
        this.groupsMap.put(group.getRoomId(), group);
        this.groups = new ArrayList<>(this.groupsMap.values());
        this.imClientNode.setGroups(this.groups);
        this.friendGroupMap = this.getGroups().stream().filter(Group::getIsFriend).collect(Collectors.toMap(Group::getFriendId, x -> x));
    }

    public void removeGroup(String roomId){
        this.groupsMap.remove(roomId);
        this.groups = new ArrayList<>(this.groupsMap.values());
        this.imClientNode.setGroups(this.groups);
        this.friendGroupMap = this.getGroups().stream().filter(Group::getIsFriend).collect(Collectors.toMap(Group::getFriendId, x -> x));
    }

}
